<template>
  <div class="depManage">
    <div class="searchBox">
      <div class="left">
        <label for="">部门名称：</label>
        <common-input
          v-model:queryCriteria.trim="queryCriteria"
          :placeholder="'请输入部门名称'"
        ></common-input>
        <label for="">状态：</label>
        <common-select
          :options="stateOptions"
          v-model="stateId"
          :placeholder="'部门状态'"
        ></common-select>
      </div>
      <div class="right">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button type="primary" @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handlePlus">新增部门</el-button>
      </div>
    </div>
    <common-table
      :style="{ flex: 1 }"
      :table-data="tableData"
      :columns="columns"
      :pagination="pagination"
    >
      <template #state="{ row }">
        <el-tag :type="row.departmentStatus == '0' ? 'success' : 'danger'">
          {{ row.departmentStatus == '0' ? '正常' : '异常' }}
        </el-tag>
      </template>
      <template #operate="{ row }">
        <el-link type="primary">
          <el-icon :size="20">
            <Edit />
          </el-icon>
          <span @click="editDep(row)">修改</span>
        </el-link>
        <el-link type="primary">
          <el-icon :size="20">
            <View />
          </el-icon>
          <span
            @click="
              () => {
                curRow = row;
                viewDepDialog = true;
              }
            "
          >
            查看
          </span>
        </el-link>
        <el-link type="primary">
          <el-icon :size="20">
            <Delete />
          </el-icon>
          <span @click="deleteDep(row)">删除</span>
        </el-link>
      </template>
    </common-table>
    <add-team-dialog
      v-if="addDepDialog"
      v-model:addDepDialog="addDepDialog"
      :prevDepOptions="prevDepOptions"
      @handleConfirm="handleConfirm"
    ></add-team-dialog>
    <edit-team-dialog
      key="999999999999999"
      :employList="employList"
      :curRow="curRow"
      :prevDepOptions="prevDepOptions"
      v-if="editTeamDialog"
      v-model:editTeamDialog="editTeamDialog"
      @handleConfirm="updateTeam"
    ></edit-team-dialog>
    <view-dep-parts
      v-if="viewDepDialog"
      v-model:viewDepDialog="viewDepDialog"
      :curRow="curRow"
    ></view-dep-parts>
  </div>
</template>
<script setup>
import CommonInput from '@/components/CommonInput.vue';
import CommonSelect from '@/components/CommonSelect.vue';
import { ref, nextTick, onMounted } from 'vue';
import CommonTable from '@/components/CommonTable.vue';
import { columns } from '@/views/depManage/mockData';
import {
  getDepManagePageList,
  deleteDep as deleteReq,
  editDepReq,
  getDepList,
  addDepReq,
  getAllEmployeeReq,
} from '@/api/depManage';
import AddTeamDialog from '@/views/depManage/components/AddTeamDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import EditTeamDialog from '@/views/depManage/components/editTeamDialog.vue';
import ViewDepParts from '@/views/depManage/components/viewDepParts.vue';

const curRow = ref(null);
const editTeamDialog = ref(false);
const viewDepDialog = ref(false);

// 任务id
const stateId = ref('');
// 任务选项
const stateOptions = ref([
  {
    label: '正常',
    value: '0',
  },
  {
    label: '异常',
    value: '1',
  },
]);

const tableData = ref([]);
// 分页
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const queryCriteria = ref('');

// 上级部门列表
const prevDepOptions = ref([]);

// 新增部门弹框显隐
const addDepDialog = ref(false);

// 新增岗位
const handlePlus = () => {
  addDepDialog.value = true;
};

const setSize = (val) => {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = val;
  getPageList();
};
const setPage = (val) => {
  pagination.value.pageNum = val;
  getPageList();
};

const handleConfirm = async (val) => {
  let par = {
    parentDepartmentId: val.prevDepId,
    departmentName: val.depName,
    departmentState: val.state,
    employeeId: val.employeeId,
  };
  const res = await addDepReq(par);
  if (res && res.code == 200) {
    getPageList();
  }
};

const processDepartmentData = (data) => {
  const processData = (item) => {
    item.id = item.departmentId;

    if (item.children && item.children.length > 0) {
      item.children.forEach(processData);
    } else {
      delete item.children;
    }
  };

  data.forEach(processData);

  return data;
};

const getPageList = async () => {
  let par = {
    currentPage: pagination.value.pageNum,
    pageSize: pagination.value.pageSize,
    stateFlag: stateId.value,
    queryCriteria: queryCriteria.value,
  };
  const res = await getDepManagePageList(par);
  if (res && res.code == '200') {
    tableData.value = processDepartmentData(res.data.allDepartmentsList);
    pagination.value.total = res.data.obtainDepartment.totalEntries * 1;
  }
};

const updateTeam = async (v) => {
  console.log(v);
  console.log('修改部门');
  let par = {
    parentDepartmentId: v.parentDepartmentId,
    departmentId: v.departmentId,
    personChargeId: v.employeeId,
    state: v.departmentStatus,
    departmentName: v.departmentName,
  };
  // 更新部门接口
  const res = await editDepReq(par);
  if (res && res.code == 200) {
    getPageList();
  }
};

// 修改部门
const editDep = (row) => {
  curRow.value = row;
  editTeamDialog.value = true;
};

// 删除部门
const deleteDep = (row) => {
  if (row?.children && row.children != 0) {
    ElMessage.error('该部门下有其他部门，请勿删除！');
  } else {
    ElMessageBox.confirm('确认删除该部门吗?', '删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        ElMessage({
          type: 'success',
          message: '删除成功！',
        });
        const res = await deleteReq({ departmentId: row.departmentId });
        getPageList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除失败！',
        });
      });
  }
};

const handleQuery = () => {
  pagination.value.pageNum = 1;
  getPageList();
};

const resetQuery = () => {
  queryCriteria.value = '';
  pagination.value.pageNum = 1;
  getPageList();
};

// 获取所有部门列表
const getAllDepList = async () => {
  const res = await getDepList();
  if (res && res.code == 200) {
    prevDepOptions.value = res.data;
    console.log(prevDepOptions.value);
  }
};

const employList = ref([]);

const getAllEmployee = async () => {
  const res = await getAllEmployeeReq();
  if (res && res.code == 200) {
    employList.value = res.data;
  }
};

// TODO 缺少接口
getPageList();
// 获取所有部门列表
getAllDepList();
// 获取负责人列表
getAllEmployee();

onMounted(() => {});

defineExpose({
  setSize,
  setPage,
});
</script>

<style scoped lang="less">
.depManage {
  background-color: #ffffff;
  flex: 1;
  max-height: 100%;
  display: flex;
  flex-direction: column;

  .searchBox {
    display: flex;
    align-items: center;
    padding: 0 24px;
    height: 32px;
    margin: 16px 0;

    .left {
      display: flex;
      align-items: center;
      margin-right: 16px;
    }

    label {
      font-size: 14px;
      color: #999999;
      margin-right: 3px;
    }
  }

  /deep/ .el-link {
    margin-right: 8px;
  }
}
</style>